<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"
	xmlns:exsl="http://exslt.org/common" version="2.0">
	<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8"/>


	<xsl:template match="/">
		<xsl:variable name="solr-url">
			<xsl:text>http://localhost:8080/solr/select/?q=</xsl:text>
		</xsl:variable>

		<xsl:variable name="name_query" select="concat($solr-url, '*:*&amp;facet.field=denomination_facet&amp;rows=0&amp;facet.sort=index&amp;facet.limit=-1')"/>
		<xsl:text>"kittredge_denomination","kittredge_state","ans_denomination","sanctioned_value","nomisma_id"</xsl:text>
		<xsl:text>
</xsl:text>

		<xsl:for-each select="document($name_query)//lst[@name='denomination_facet']/int">
			<xsl:variable name="first_value" select="@name"/>
			<!--<xsl:variable name="geonameId" select="document(concat('http://api.geonames.org/search?q=', $first_value, '&amp;username=anscoins&amp;style=full'))//geoname[1]/descendant::geonameId"/>-->
			<xsl:variable name="second_field">state_facet</xsl:variable>
			
			<xsl:variable name="state_query"
				select="concat($solr-url, 'denomination_facet:%22', $first_value, '%22&amp;facet.field=', $second_field, '&amp;rows=0&amp;facet.sort=index&amp;facet.limit=-1')"/>
			<xsl:variable name="no_state_query" select="concat($solr-url, 'NOT ', $second_field, ':* AND denomination_facet:%22', $first_value, '%22&amp;rows=0')"/>

			<xsl:for-each select="document($state_query)//lst[@name=$second_field]/int">
				<xsl:variable name="second_value" select="@name"/>
				<!--<xsl:variable name="viaf-query" select="concat('http://viaf.org/viaf/search?query=local.mainHeadingEl+all+%22', $first_value, '%22+and+local.sources+any+%22lc%22&amp;httpAccept=application/rss%2bxml&amp;maximumResults=1')"/>
				<xsl:variable name="viaf-link" select="document($viaf-query)//item[1]/link"/>-->


				<xsl:text>"</xsl:text>
				<xsl:value-of select="$first_value"/>
				<xsl:text>","</xsl:text>
				<xsl:value-of select="$second_value"/>
				<xsl:text>","","",""</xsl:text>
				<xsl:text>
</xsl:text>
			</xsl:for-each>
			<xsl:if test="number(document($no_state_query)//result[@name='response']/@numFound) &gt; 0">
				<xsl:text>"</xsl:text>
				<xsl:value-of select="$first_value"/>
				<xsl:text>","","","",""</xsl:text>
				<xsl:text>
</xsl:text>
			</xsl:if>
		</xsl:for-each>
	</xsl:template>
</xsl:stylesheet>
